package cn.virens.common.fastjson.serializer;

import cn.virens.common.exception.APIException;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.writer.ObjectWriter;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Objects;
import java.util.function.BiFunction;

public final class BigDecimalSerializer implements ObjectWriter<Object>, BiFunction<String, Object, Object> {
    public final static BigDecimalSerializer instance = new BigDecimalSerializer();

    public final static DecimalFormat FORMAT = new DecimalFormat("#.###");

    private BigDecimalSerializer() {
    }

    @Override
    public void write(JSONWriter jsonWriter, Object fieldObject, Object fieldName, Type fieldType, long features) {
        if (jsonWriter != null && fieldObject != null && fieldObject instanceof BigDecimal value) {
            jsonWriter.writeString(apply(Objects.toString(fieldName), value).toString());

            return;
        }

        jsonWriter.writeNull();
    }

    @Override
    public Object apply(String name, Object object) throws APIException {
        if (object instanceof BigDecimal value) {
            return FORMAT.format(value);
        } else {
            return object;
        }
    }

}
